﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestHttpModules
{
    using System.Configuration;
    using System.Data.SqlClient;
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        static readonly string ServerName = ConfigurationManager.AppSettings["ServerName"];
        static readonly string ServerIP = ConfigurationManager.AppSettings["ServerIP"];
        static readonly string DBIP = ConfigurationManager.AppSettings["DBIP"];
        static readonly string DBName = ConfigurationManager.AppSettings["DBName"];
        static readonly string DBUser = ConfigurationManager.AppSettings["DBUser"];
        static readonly string DBPassword = ConfigurationManager.AppSettings["DBPassword"];
        static readonly string conn = string.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;
                                 User Instance=False;User ID={2};Password={3};MultipleActiveResultSets=true"
             , DBIP
             , DBName
             , DBUser
             , DBPassword);
        public void ProcessRequest(HttpContext context)
        {
            string str = string.Empty;
            string callback = context.Request["jsonpcallback"];
            context.Response.ContentType = "application/x-javascript";
            str = callback + "({" + string.Format("\'ServerName\':\'{0}\', \'ServerIP\':\'{1}\',\'IISMessage\':\'{2}\',\'DBMessage\':\'{2}\'", ServerName, ServerIP, "ok", TestDB()) + "})";
            context.Response.Write(str);

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string TestDB()
        {
            string message = "false";
            try
            {
                if (string.IsNullOrEmpty(conn))
                    throw new Exception("请设置config.config里的数据连接字符串DB");

                using (SqlConnection _conn = new SqlConnection(conn))
                {
                    using (SqlCommand comm = new SqlCommand("SELECT COUNT(1)  FROM sys.tables", _conn))
                    {
                        try
                        {
                            comm.ExecuteReader();
                        }
                        catch (Exception)
                        {
                            message = "Fail";
                        }

                    }
                }
                message = "OK";
            }
            catch (Exception)
            {
                message = "Fail";
            }
            return message;
        }
    }
}